package com.mayikt.pay.wechat.handler;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.mayikt.pay.wechat.builder.TextBuilder;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }

      /*  //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                && weixinService.getKefuService().kfOnlineList()
                .getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser()).build();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }*/

        //TODO 组装回复消息
        //String content = "收到信息内容：" + JsonUtils.toJson(wxMessage);
        String content =wxMessage.getContent();
       HashMap hashMap= new HashMap<>();
       hashMap.put("key","free");
       hashMap.put("appid","0");
       hashMap.put("msg",content);

        try {
            // 调用第三方智能接口  获取关键字匹配
            String result = HttpUtil.get("http://api.qingyunke.com/api.php", hashMap);
            logger.info("result:{}", result);
            if (StringUtils.isEmpty(result)) {
                return setResult("系统忙，请稍后重试!", wxMessage, weixinService);
            }
            JSONObject json = JSONObject.parseObject(result);
            Integer code = json.getInteger("result");
            if (0!=code) {
                return setResult("系统忙，请稍后重试!", wxMessage, weixinService);
            }
            // 调用接口成功 获取 智能接口中响应的内容
            String resultContent = json.getString("content");
            return setResult(resultContent, wxMessage, weixinService);
        } catch (Exception e) {
            logger.error("e:{}", e);
            return setResult("系统忙，请稍后重试!", wxMessage, weixinService);
        }


    }
    private WxMpXmlOutMessage setResult(String content, WxMpXmlMessage wxMessage,
                                        WxMpService service) {
        return new TextBuilder().build(content, wxMessage, service);
    }
}
